/**
 * 入参
 *  type：1-指令新增   2-簿记新增    3-簿记详情   4-交收   5-中签
    info：type=3 || 4 ||5时，需回填字段
    onRef：组件指针
    deposit：定金，由主框架传入，默认是undefined；
    depositRate：定金比例，由主框架传入，默认是undefined；
    getInfo：通过onRef，调用getInfo方法，获取各字段的值，在getInfo中完成校验，若校验不通过，返回undefined
    productOnChange：产品变更事件，输出当前产品ID，若无则为undefined；
    portfolioOnChange：组合变更事件，输出当前组合ID，若无则为undefined；
    tradingcodeOnChange：证券代码变更事件，输出当前证券code，若无则为undefined。
 */
import React, { PureComponent } from 'react';
import { DATA_ENTRY, FormGroup, codeType } from '../../../../comps';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import style from './index.less';
import { connect } from 'dva';
import moment from 'moment';
import investmentType from '../../../../utils/enumeratedValues/investmentType';
import { calculateFee } from '../../../../utils/commonFunc';

class OrderFormC extends PureComponent {
  static defaultProps = {
    onRef: () => {},
    portfolioOnChange: () => {},
    productOnChange: () => {},
    tradingcodeOnChange: () => {},
  };
  state = {
    info: undefined, //etf详情
    type: undefined, //当前指令的类型type：1-指令新增   2-簿记新增    3-簿记详情
    SecuritiesCode: undefined, //证券代码val值
    bussniessVisible: false, //业务目标编辑补充是否可见
    addSPPIFlag: false, //点击了新增测试按钮
    SPPI_result: undefined, //根据证券代码获取sppi结果
    objectives: undefined, //选中的业务目标
    objectivesEditObj: {}, //缓存每一个业务目标对应的编辑
    editContent: {}, //业务目标编辑内容
    investmentTypeList: [...investmentType], //投资类型下拉
    feeData: {
      //费用自动计算条件
      productId: undefined,
      portfolioid: undefined,
      tradingCode: undefined,
      exchangecode: undefined,
      sectype: 'zqwxsg',
      orderside: undefined,
      price: undefined,
    },
  };
  componentDidMount() {
    this.props.onRef(this);
    if (this.props.type > 2) {
      //详情时取业务目标的值
      this.setState({
        objectives: this.props.info ? this.props.info.trade17.bussinessObjectives : undefined,
        editContent: this.props.info ? this.props.info.trade17 : {},
      });
    }
  }

  //费用自动计算
  changeFee = (type, data) => {
    const {
      form: { setFieldsValue },
    } = this.formGroupThis.props;
    if (this.props.type == 3 || this.props.type == 5) return; //详情不计算
    setTimeout(() => {
      if (data == undefined) {
        setFieldsValue({ 'trade17.fee': undefined });
        if (type == 'tradingCode') {
          this.setState({ feeData: { ...this.state.feeData, tradingCode: undefined, exchangecode: undefined } });
        } else if (type == 'productId') {
          this.setState({ feeData: { ...this.state.feeData, productId: undefined, portfolioid: undefined } });
        } else {
          this.setState({ feeData: { ...this.state.feeData, [type]: undefined } });
        }
      } else {
        if (type == 'tradingCode') {
          this.setState({ feeData: { ...this.state.feeData, tradingCode: data.tradingCode, exchangecode: data.exchangeCode } }, () => {
            let fee = calculateFee(this.state.feeData);
            fee.then((r) => {
              setFieldsValue({ 'trade17.fee': r });
            });
          });
        } else {
          this.setState({ feeData: { ...this.state.feeData, [type]: data } }, () => {
            let fee = calculateFee(this.state.feeData);
            fee.then((r) => {
              setFieldsValue({ 'trade17.fee': r });
            });
          });
        }
      }
    }, 100);
  };

  //组合改变
  groupOnChange = (value) => {
    //抛出组合id
    let val;
    if (value) val = value.key;
    this.props.portfolioOnChange(val);
  };
  //产品改变
  productOnChange = (value) => {};
  //计算定金
  calc = (e, type) => {
    const {
      form: { getFieldValue, setFieldsValue },
    } = this.formGroupThis.props;
    const { SecuritiesCode } = this.state;
    if (!SecuritiesCode) return;
    if (SecuritiesCode.prepaindProp && SecuritiesCode.prepaindAmount) return; //定金和定金比例二者只能有一个
    let amount = type == 'amount' ? e : getFieldValue('trade17.amount'); //申购金额
    //若按照固定保证金，取固定金额；若是比例，则根据申购金额*定金比例计算
    setFieldsValue({
      trade17: {
        deposit: SecuritiesCode.prepaindProp ? (amount ? parseFloat(SecuritiesCode.prepaindProp * amount) : undefined) : SecuritiesCode.prepaindAmount,
      },
    });
  };
  //证券代码切换
  securitiesCodeChange = (value) => {
    const {
      form: { setFieldsValue },
    } = this.formGroupThis.props;
    const { info } = this.props;
    if (info) return; //详情时不进入判断
    this.setState(
      {
        SecuritiesCode: value,
      },
      () => {
        this.getSPPI_Result();
        if (!value) return;
        this.calc();
      },
    );
    setFieldsValue({
      trade17: {
        exchangeCode: value ? value.exchangeCode : undefined,
      },
    });
    this.props.tradingcodeOnChange(value);
  };
  //获取sppi结果
  getSPPI_Result = () => {
    const { SecuritiesCode } = this.state;
    if (this.props.type < 3) {
      if (!SecuritiesCode) {
        this.setState(
          {
            SPPI_result: undefined,
          },
          () => {
            this.formGroupThis.props.form.setFieldsValue({
              SPPI_result: this.state.SPPI_result,
            });
            this.setSelectList();
          },
        );
        return;
      }
      this.props.dispatch({
        type: 'bondTradeM/getSPPIResult',
        payload: {
          exchangeCode: SecuritiesCode.exchangeCode,
          tradingCode: SecuritiesCode.tradingCode,
        },
        callback: (data) => {
          let temp;
          if (data) {
            //sppi有值 不可点击新增按钮  无值可以
            temp = data.rgpd;
          } else {
            temp = undefined;
          }
          this.setState(
            {
              SPPI_result: temp,
            },
            () => {
              this.formGroupThis.props.form.setFieldsValue({
                SPPI_result: this.state.SPPI_result,
              });
              this.setSelectList();
            },
          );
        },
      });
    }
  };
  //设置投资类型下拉 并确定默认值
  setSelectList = () => {
    // 以收取该金融资产合同现金流量为目的	是	AC
    // 以收取该金融资产合同现金流量为目的	否	FVTPL
    // 以收取该合同现金流量及出售金融资产为目的	是	FVOCI
    // 以收取该合同现金流量及出售金融资产为目的	否	FVTPL
    // 其他	是 or 否	FVTPL
    const { SPPI_result, objectives } = this.state;
    const {
      form: { setFieldsValue },
    } = this.formGroupThis.props;
    if (SPPI_result == undefined || objectives == undefined) {
      setFieldsValue({
        trade17: {
          investmentType: undefined,
        },
      });
      this.setState({
        investmentTypeList: investmentType,
      });
      return;
    }
    let arr = [];
    if (objectives == 1 && SPPI_result == 1) {
      //AC
      arr = [{ value: 'AC', title: 'AC' }];
      setFieldsValue({
        trade17: {
          investmentType: 'AC',
        },
      });
    } else if ((objectives == 1 && SPPI_result == 2) || (objectives == 2 && SPPI_result == 2) || (objectives == 4 && SPPI_result)) {
      //FVTPL
      arr = [{ value: 'FVTPL', title: 'FVTPL' }];
      setFieldsValue({
        trade17: {
          investmentType: 'FVTPL',
        },
      });
    } else if (objectives == 2 && SPPI_result == 1) {
      //FVOCI
      arr = [{ value: 'FVOCI', title: 'FVOCI' }];
      setFieldsValue({
        trade17: {
          investmentType: 'FVOCI',
        },
      });
    } else {
      arr = [...investmentType];
      setFieldsValue({
        trade17: {
          investmentType: undefined,
        },
      });
    }
    this.setState({
      investmentTypeList: [...arr],
    });
  };

  //业绩目标修改
  changeObjectives = (e) => {
    this.setState(
      {
        objectives: e,
      },
      () => {
        this.setSelectList();
      },
    );
  };
  //获取当前表单数据 并校验
  getInfo = () => {
    const {
      user: { currentUser },
      type,
    } = this.props;
    const {
      form: { validateFields },
    } = this.formGroupThis.props;
    let query = undefined;
    const { objectives, objectivesEditObj } = this.state;
    let obj = objectivesEditObj[objectives];
    validateFields((err, fieldsValue) => {
      if (!err) {
        query = fieldsValue;
        if (type == 5) return; //如果是中签
        query.userId = currentUser.userId;
        query.userName = currentUser.name;
        query.trade17.tradingCode = this.state.SecuritiesCode.tradingCode;
        query.trade17.sppiResult = query.trade17.SPPI_result; //修改入参名
        query.trade17.fee = 0; // 费用计算逻辑未完全梳理清楚，后续用户有真正需求时再添加费用计算相关逻辑
        delete query.trade17.SPPI_result;
        delete query.zqdm;
        if (obj) {
          query.trade17 = { ...query.trade17, ...obj };
        }
      }
    });
    return query;
  };
  //重置页面数据 取消
  reset = () => {
    const { form } = this.formGroupThis.props;
    this.props.portfolioOnChange(undefined);
    this.props.tradingcodeOnChange(undefined); //重置组合id和证券代码
    form.resetFields();
    this.setState({
      bussniessVisible: false, //业务目标编辑补充是否可见
      addSPPIFlag: false, //点击了新增测试按钮
      SPPI_result: undefined, //根据证券代码获取sppi结果
      objectives: undefined, //选中的业务目标
      objectivesEditObj: {}, //缓存每一个业务目标对应的编辑
      editContent: {}, //业务目标编辑内容
      investmentTypeList: [...investmentType], //投资类型下拉
      SecuritiesCode: undefined,
    });
  };
  //校验申购金额
  validatorFun = (rule, value, callback) => {
    var r = /^[1-9]\d*00$/;
    if (value && !r.test(value)) {
      callback('必须100的整数倍!');
    }
    callback();
  };
  //计算申购金额
  quantityChange = (value) => {
    const { form } = this.formGroupThis.props;
    form.setFieldsValue({
      realAmount: parseFloat(value * 100),
    });
  };

  //form表单渲染
  formRender = () => {
    const { type, info } = this.props;
    let disabled;
    const { SPPI_result, SecuritiesCode, investmentTypeList } = this.state;
    const {
      globalM: {
        dataDictionary: { SPPI_USER_DEFINEDTYPE = [] },
      },
    } = this.props;
    const tenant = localStorage.getItem('antd-pro-tenant');
    if (type == 1 || type == 2) {
      disabled = false;
    } else {
      disabled = true;
    }
    return (
      <div className={'formOrder'}>
        <FormGroup
          dataSource={[
            {
              disabled: disabled,
              type: DATA_ENTRY.PRODUCTGROUPSEP,
              title: ['产品', '组合'],
              initialValue: info ? [info.productId, info.portfolioId] : undefined,
              authority: 'write',
              multipleGroup: false,
              dataIndex: ['productId', 'portfolioId'],
              rules: [[{ required: true, message: '请选择产品!' }], [{ required: true, message: '请选择组合!' }]],
              groupOnChange: (e) => {
                this.groupOnChange(e);
                this.changeFee('portfolioid', e?.key);
                this.props.portfolioCode(e ? e.info.portfolioCode : undefined); //向外抛出组合code
              },
              productOnChange: (e) => {
                this.changeFee('productId', e?.key);
                this.props.productCode(e ? e.info.portfolioCode : undefined); //向外抛出产品code
              },
              allowClear: false,
              exist: 1,
              span: 24,
              tradeModel: type == 1 || type == 2 ? ['BOOKKEEPING_MODE', 'COMMAND_MODE'] : undefined, //不包含估值解析和估值对接的产品
            },
            {
              dataIndex: 'zqdm',
              type: DATA_ENTRY.SECURITIESCODE,
              title: '证券代码',
              initialValue: info ? `${info.trade17.exchangeCode}-${info.trade17.tradingCode}` : undefined,
              onChange: (e) => {
                this.securitiesCodeChange(e);
                this.changeFee('tradingCode', e ? e : undefined);
              },
              codeType: codeType.fxBond,
              rules: [{ required: true, message: '请选择证券代码!' }],
              disabled: disabled,
              queryItems: { time: moment(new Date()).format('YYYY-MM-DD') },
              span: 12,
            },
            {
              title: '交易市场',
              dataIndex: 'trade17.exchangeCode',
              type: DATA_ENTRY.TRADINGMARKET,
              dataType: 1,
              initialValue: type > 2 ? info.trade17.exchangeCode : undefined,
              marketType: ['jys', 'yhj'],
              rules: [{ required: true, message: '请选择交易市场!' }],
              disabled: true,
              span: 12,
              onRef: (ref) => (this.formGroupThis = ref),
            },
            {
              title: '交易方向', // 显示名称
              dataIndex: 'trade17.orderSide', // Form识别的Item ID
              type: DATA_ENTRY.TRADINGDIRECT,
              businessType: '17',
              initialValue: info ? info.trade17.orderSide : '1',
              disabled: true,
              onChange: (e) => this.changeFee('orderside', e?.value),
              rules: [{ required: true, message: '请选择交易方向!' }],
              span: 12,
            },
            {
              dataIndex: 'trade17.amount',
              title: '申购金额',
              type: DATA_ENTRY.INPUTNUMBER,
              unit: '元',
              min: 10000,
              initialValue: info ? info.trade17.amount : undefined,
              splitStyle: true,
              rules: [{ required: true, message: '请输入申购金额!' }, { validator: this.validatorFun }],
              onChange: (e) => {
                this.calc(e, 'amount'), this.changeFee('price', e ? e : undefined);
              },
              precision: 2,
              disabled: disabled,
              span: 12,
            },
            {
              dataIndex: 'trade17.deposit',
              title: '定金',
              type: DATA_ENTRY.INPUTNUMBER,
              unit: '元',
              initialValue: info ? info.trade17.deposit : undefined,
              splitStyle: true,
              rules: [{ required: true, message: '请输入定金!' }],
              disabled: true,
              precision: 2,
              span: 12,
            },
            // {
            //   dataIndex: 'trade17.fee',
            //   title: '费用',
            //   type: DATA_ENTRY.INPUTNUMBER,
            //   unit: '元',
            //   min: 0,
            //   initialValue: info ? info.trade17.fee : 0,
            //   splitStyle: true,
            //   rules: [{ required: false, message: '请输入费用!' }],
            //   precision: 2,
            //   disabled: type != 5 ? disabled : false,
            //   span: 12
            // },
            ...(type > 3 || (info && info.trade17.realAmount)
              ? [
                  {
                    dataIndex: 'quantity',
                    title: '中签数量',
                    type: DATA_ENTRY.INPUTNUMBER,
                    initialValue: info ? info.trade17.quantity : undefined,
                    splitStyle: true,
                    precision: 0,
                    onChange: this.quantityChange,
                    rules: [
                      { required: true, message: '请输入中签数量!' },
                      {
                        validator: (rule, value, callback) => {
                          if (value === 0) {
                            callback('必须大于0!');
                          }
                          callback();
                        },
                      },
                    ],
                    disabled: type == 4 || type == 3 ? true : false,
                    span: 12,
                  },
                  {
                    dataIndex: 'realAmount',
                    title: '中签金额',
                    type: DATA_ENTRY.INPUTNUMBER,
                    precision: 2,
                    initialValue: info ? info.trade17.realAmount : undefined,
                    splitStyle: true,
                    rules: [{ required: true, message: '请输入中签金额!' }],
                    disabled: true,
                    span: 12,
                  },
                ]
              : []),
            ...(type < 6
              ? [
                  {
                    //业务目标
                    dataIndex: 'bussinessObjectives',
                    type: DATA_ENTRY.BUSINESSTARGETC,
                    disabled: type == '3' || type == '4' ? true : false,
                    initialValue: type == '3' || type == '4' ? info?.trade17?.bussinessObjectives : undefined,
                    onChangeFn: this.changeObjectives,
                    TaretType: type,
                    info: this.state.editContent,
                    getLayerValue: this.getObjectEdit,
                    span: 24,
                  },
                  {
                    dataIndex: 'SPPI_result',
                    type: DATA_ENTRY.SPPIRESULTC,
                    title: 'SPPI结果',
                    initialValue: type == '3' || type == '4' ? info.trade17.sppiResult : undefined,
                    selectProps: {
                      SecuritiesCode,
                      rightContentShow: type < 3 ? true : false, //右侧按钮是否展示，后面展示后的禁用逻辑，展示逻辑，组件控制
                      SPPI_result: SPPI_result, //根据证券代码切换获取SPPI结果
                      SppItype: 3,
                      sppITitle: '新增测试',
                    },
                    onOk: this.getSPPI_Result, //新增完了 重新获取结果
                    span: 12,
                  },
                  {
                    dataIndex: 'trade17.investmentType',
                    type: DATA_ENTRY.SELECT,
                    title: '投资类型',
                    disabled: disabled,
                    initialValue: type > 2 ? info.trade17.investmentType : undefined,
                    dataSource: investmentTypeList,
                    span: 12,
                  },
                ]
              : []),
            ...(type < 6 && tenant == 'XAYH'
              ? [
                  {
                    dataIndex: 'trade17.userDefinedType',
                    type: DATA_ENTRY.SELECT,
                    title: '自定义分类',
                    disabled: disabled,
                    initialValue: type > 2 ? info.trade17.userDefinedType : undefined,
                    dataSource: SPPI_USER_DEFINEDTYPE.map((item) => {
                      return { value: item.code, title: item.value };
                    }),
                    span: 12,
                  },
                ]
              : []),
            {
              dataIndex: 'trade17.remark',
              type: DATA_ENTRY.INPUT,
              title: '备注',
              disabled: disabled,
              initialValue: info ? info.trade17.remark : undefined,
              placeholder: '请输入',
              showTextArea: true,
              autosize: { minRows: 2, maxRows: 2 },
              span: 24,
            },
          ]}
          autoLayout={false}
        />
      </div>
    );
  };
  //存储每一个业绩目标对应的补充编辑
  getObjectEdit = (objectivesEditObj) => {
    this.setState({
      objectivesEditObj,
    });
  };

  render() {
    return <div className={style.info}>{this.formRender()}</div>;
  }
}
export default connect(({ nonstandardOrderM, globalM, userM: user, loading }) => ({
  nonstandardOrderM,
  globalM,
  user,
  loading,
}))(Form.create()(OrderFormC));
